package com.noahsloan.nutils.streams;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Wrapper around an stream that checks for an error from a future object
 * whenever a read is performed. The idea is that the underlying stream may not
 * have enough information to know an error occurred.
 * 
 * TODO use this class.
 * 
 * @author noah
 * 
 */
public class CheckErrorInputStream extends FilterInputStream {

    private IOException e;

    public CheckErrorInputStream(InputStream in) {
        super(in);
    }

    @Override
    public int read() throws IOException {
        check();
        return super.read();
    }

    @Override
    public int read(byte[] b) throws IOException {
        check();
        return super.read(b);
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        check();
        return super.read(b, off, len);
    }

    private void check() throws IOException {
        if (e != null) {
            throw e;
        }
    }

    public void setException(IOException e) {
        this.e = e;
    }
}
